package com.springboot.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.db.ds.DSFactory;
import cn.hutool.db.ds.GlobalDSFactory;
import cn.hutool.setting.Setting;
import com.alibaba.fastjson.JSON;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Data
@Configuration
// 找配置文件 先找jar包平级目录的 先加载.properties 找不到就找.yml 找不到再找classpath下的
// ignoreResourceNotFound = true 是让他找不到文件的时候不报错继续往下找
@PropertySource(value = {"file:${user.dir}/config/db.yml"}, factory = YamlPropertySourceFactory.class)
public class MutiplyDataSourceRunner implements ApplicationRunner {

    @Value("${db.url}")
    private String url;

    @Value("${db.user}")
    private String user;

    @Value("${db.pass}")
    private String pass;

    @Value("${db.showSql}")
    private String showSql;

    @Value("${db.formatSql}")
    private String formatSql;

    @Value("${db.showParams}")
    private String showParams;

    @Value("${db.sqlLevel}")
    private String sqlLevel;

    /**
     * 项目启动后会自动执行一次这个方法
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        Setting setting = new Setting();
        setting.putAll(getConfigMap(this));
        try {
            GlobalDSFactory.set(DSFactory.create(setting));
        } catch (Exception e) {
            log.error("加载多数据源异常，{}", e);
        } finally {
            log.info("================设置全局hutool数据源完毕================");
        }
    }

    private Map<String, String> getConfigMap(Object obj) {
        Map<String, String> configMap = new HashMap<>();
        Map<String, Object> thisBeanMap = BeanUtil.beanToMap(obj);
        for (Map.Entry<String, Object> entry : thisBeanMap.entrySet()) {
            configMap.put(entry.getKey(), String.valueOf(entry.getValue()));
        }
        log.info("read mutiply datasource configMap = {}", JSON.toJSONString(configMap));
        return configMap;
    }
}